<?php

namespace app\bll;

use app\validate\SiteAdmin as ValidateSiteAdmin;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use support\Db;

/**
 * 站点管理员
 */
class SiteAdmin
{

    /**
     * 根据ID查询
     *
     * @param integer $id
     * @param integer $siteid
     * @return array
     */
    public function find(int $id, int $siteid): array
    {
        $data =  Db::table('frame_site_admin')
            ->leftJoin('frame_user', 'frame_user.id', '=', 'frame_site_admin.uid')
            ->where('frame_site_admin.id', '=', $id)
            ->where('frame_site_admin.siteid', '=', $siteid)
            ->first(['frame_user.username', 'frame_user.phone', 'frame_site_admin.*']);
        return $data === null ? [] : get_object_vars($data);
    }



    /**
     * 某用户在某站点的管理员信息
     *
     * @param integer $uid
     * @param integer $siteid
     * @return array
     */
    public function findByUid(int $uid, int $siteid): array
    {
        $data =  Db::table('frame_site_admin')
            ->where('uid', '=', $uid)
            ->where('siteid', '=', $siteid)
            ->first();

        return $data === null ? [] : get_object_vars($data);
    }


    /**
     * 查询某用户所拥有的站点id
     *
     * @param integer $uid
     * @return array
     */
    public function selectSiteIdsByUid(int $uid): array
    {
        return  Db::table('frame_site_admin')
            ->where('uid', '=', $uid)
            ->value('siteid')
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 某用户可管理的站点
     *
     * @param array $uid
     * @return array
     */
    public function UserManageableSite(int|array $user): array
    {
        if (is_array($user)) {
            $uid = $user['id'];
        } else {
            $uid = $user;
        }

        return Db::table('frame_site_admin')
            ->leftJoin('frame_site', 'frame_site.id', '=', 'frame_site_admin.siteid')
            ->where('frame_site_admin.uid', '=', $uid)
            ->get(['frame_site.*', 'frame_site_admin.issuperadmin'])
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 查询站点管理员
     *
     * @param integer $siteid
     * @param integer|null $issuperadmin
     * @return array
     */
    public function selectBySiteid(int $siteid, ?int $issuperadmin = null): array
    {
        return  Db::table('frame_site_admin')
            ->leftJoin('frame_user', 'frame_site_admin.uid', '=', 'frame_user.id')
            ->leftJoin('frame_user_basicinfo', 'frame_user.id', '=', 'frame_user_basicinfo.uid')
            ->where('siteid', '=', $siteid)
            ->when($issuperadmin !== null, function ($query) use ($issuperadmin) {
                return $query->where('issuperadmin', '=', $issuperadmin);
            })
            ->get(['frame_user.*', 'frame_user_basicinfo.name'])
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 
     * 根据用户ID和站点ID获取
     * @param integer $uid
     * @param integer $siteid
     * @return array
     */
    public function findByUidSiteid(int $uid, int $siteid): array
    {
        $admininfo =  Db::table('frame_site_admin')
            ->where('uid', '=', $uid)
            ->where('siteid', '=', $siteid)
            ->first();

        return $admininfo === null ? [] : get_object_vars($admininfo);
    }


    /**
     * 添加站点管理员
     *
     * @param array $data
     * @throws Exception
     * @return void
     */
    public function add(array $data)
    {

        $ValidateSiteAdmin = new ValidateSiteAdmin();
        if (!$ValidateSiteAdmin->check($data)) {
            throw new Exception($ValidateSiteAdmin->getSimpleError());
        }

        Db::beginTransaction();
        try {
            $bllAdmin = new Admin();
            $admininfo = $bllAdmin->findByUid($data['uid']);
            //判断admin 表里有无数据
            if (!$admininfo) {
                Db::table('frame_admin')
                    ->insert([
                        'uid' => $data['uid'],
                        'issystem' => 0
                    ]);
            }

            $siteadmininfo = $this->findByUidSiteid(
                uid: $data['uid'],
                siteid: $data['siteid']
            );
            if (isset($data['roleids']) && $data['roleids']) {
                if (is_array($data['roleids'])) {
                    $data['roleids'] = ',' . implode(',', $data['roleids']) . ',';
                }
                if (is_string($data['roleids'])) {
                }
                $data['roleids'] = ',' . trim($data['roleids'], ',') . ',';
            }
            if ($siteadmininfo) {
                //修改站点管理员
                Db::table('frame_site_admin')
                    ->where('uid', '=', $data['uid'])
                    ->where('siteid', '=', $data['siteid'])
                    ->update($data);
            } else {
                //添加到站点管理员表
                Db::table('frame_site_admin')
                    ->insertGetId($data);
            }
            Db::commit();
        } catch (Exception $ex) {
            Db::rollBack();
            throw $ex;
        }
    }


    public function edit(int $id, int $siteid, array $data)
    {
        $data['siteid']    = $siteid;
        $ValidateSiteAdmin = new ValidateSiteAdmin();
        if (!$ValidateSiteAdmin->check($data)) {
            throw new Exception($ValidateSiteAdmin->getSimpleError());
        }

        //修改站点管理员

        if (isset($data['roleids']) && $data['roleids']) {
            if (is_array($data['roleids'])) {
                $data['roleids'] = ',' . implode(',', $data['roleids']) . ',';
            }
            if (is_string($data['roleids'])) {
            }
            $data['roleids'] = ',' . trim($data['roleids'], ',') . ',';
        }

        return  Db::table('frame_site_admin')
            ->where('uid', '=', $data['uid'])
            ->where('siteid', '=', $data['siteid'])
            ->update($data);
    }

    /**
     * 删除站点管理员
     *
     * @param integer $uid
     * @param integer $siteid
     * @return void
     */
    public function delete(int $uid, int $siteid)
    {

        Db::beginTransaction();
        try {
            $bllAdmin = new Admin();
            $admininfo = $bllAdmin->findByUid($uid);

            //不是系统管理员删除
            if ($admininfo && $admininfo['type'] == 0) {

                $count = Db::table('frame_site_admin')
                    ->where('uid', '=', $uid)
                    ->where('siteid', '<>', $siteid)
                    ->count();
                if ($count == 0) {
                    Db::table('frame_admin')->where('uid', '=', $uid)
                        ->delete();
                }
            }

            Db::table('frame_site_admin')
                ->where('uid', '=', $uid)
                ->delete();
            Db::commit();
        } catch (Exception $ex) {
            Db::rollBack();
            return $ex;
        }
    }

    /**
     * 分页查询
     *
     * @param string $name
     * @param string $ident
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginator(
        int $siteid = 0,
        string $username_phone = '',
        int $pagesize = 20
    ): LengthAwarePaginator {
        return  Db::table('frame_site_admin')
            ->leftJoin('frame_user', 'frame_user.id', '=', 'frame_site_admin.uid')
            ->when($username_phone != '', function ($query) use ($username_phone) {
                return $query->where('frame_user.username', 'like', '%' . $username_phone . '%')
                    ->orWhere('frame_user.phone', 'like', '%' . $username_phone . '%');
            })
            ->when($siteid != 0, function ($query) use ($siteid) {
                return $query->where('frame_site_admin.siteid', '=', $siteid);
            })
            ->orderBy('frame_user.id', 'desc')
            ->paginate(
                perPage: $pagesize,
                columns: ['frame_user.username', 'frame_user.phone', 'frame_site_admin.*']
            );
    }
}
